package httputils

import (
	"bytes"
	"encoding/json"
	"fx_swift_schedule/api"
	"fx_swift_schedule/pkg/logger"
	"io"
	"net/http"
	"time"
)

// HTTPPost 发送HTTP POST请求
func HTTPPost(url string, headers map[string]string, body []byte) (*http.Response, error) {
	// 创建一个字节数组缓冲区，用于存储请求体数据
	buffer := bytes.NewBuffer(body)

	// 创建一个http请求对象
	req, err := http.NewRequest("POST", url, buffer)
	if err != nil {
		return nil, err
	}

	// 设置请求头信息
	for key, value := range headers {
		req.Header.Set(key, value)
	}

	// 发送请求，并获取响应对象
	client := http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		return nil, err
	}

	return resp, nil
}

func RestFulGet(urls string, headers map[string]string) (*http.Response, error) {
	req, err := http.NewRequest("GET", urls, nil)
	if headers != nil {
		for key, value := range headers {
			req.Header.Set(key, value)
		}
	}
	// 发送请求，并获取响应对象
	client := http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

func GetRequestParam(tradeCode, accessToken string) map[string]interface{} {
	req := make(map[string]interface{})
	//封装请求头head
	requestHead := make(map[string]interface{})
	requestHead["language"] = "cn"
	requestHead["tradeCode"] = tradeCode
	requestHead["tradeTime"] = time.Now().Unix()
	requestHead["version"] = "1.0.0"
	requestHead["tradeType"] = "00"
	//accessToken依据接口需要进行组装
	if accessToken != "" {
		requestHead["accessToken"] = accessToken
	}
	req["head"] = requestHead

	return req
}

// post请求
func DoPost(url string, data []byte) (resp string) {
	response, _ := http.DefaultClient.Post(url, "application/json", bytes.NewReader(data))
	if response.StatusCode != 200 {
		respData := api.JsonStr{}
		body, _ := io.ReadAll(response.Body)
		json.Unmarshal(body, &respData)
		logger.SugarLogger.Error(respData.Head.RespDesc)
		return ""
	}
	bodyByte, err := io.ReadAll(response.Body)
	if err != nil {
		logger.SugarLogger.Errorf("json 读取报错:%w", err)
		return ""
	}
	resp = string(bodyByte)
	return resp
}
